package com.paishen.peiniwan.module.date;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.LogUtil;
import com.paishen.libalipay.PayManager;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.Coupon;
import com.paishen.peiniwan.database.CouponDao;
import com.paishen.peiniwan.database.User;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.Balance;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import de.greenrobot.event.EventBus;


public class DatePayInfoLayout extends FrameLayout {

    private OnCouponClickListener callback;

    public interface OnCouponClickListener {
        void onCouponClick();
    }

    public void setOnCouponClickListener(OnCouponClickListener callback) {
        this.callback = callback;
    }

    private static final int WAY_ALI = 1;
    private static final int WAY_BALANCE = 2;
    private int currWay = WAY_ALI;

    private final View layCoupon;
    private final TextView txPrice, txCoupon, txCouponTitle, txFinalPrice, txBalanceInfo;
    private final ImageView imgCoupon;
    private final Button btnUp;
    private final ImageView imgAli, imgBlance;


    private Coupon selectedCoupon;
    private long oid, bookid;
    private float price;
    private float originalPrice;

    private Random random = new Random();

    private   String makeRandomValue(int length) {
        if (length < 16) length = 16;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    public DatePayInfoLayout(Context context) {
        this(context, null);
    }

    public DatePayInfoLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_date_pay_info, this);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        txPrice = (TextView) findViewById(R.id.tx_price);
        txCoupon = (TextView) findViewById(R.id.tx_coupon);
        txCouponTitle = (TextView) findViewById(R.id.tx_coupon_title);
        txFinalPrice = (TextView) findViewById(R.id.tx_final_price);
        txBalanceInfo = (TextView) findViewById(R.id.tx_balance_info);
        Float amount = App.i().getUser().getAmount();
        int result = amount != null ? (int) amount.floatValue() : 0;
        txBalanceInfo.setText(context.getString(R.string.date_pay_way_balance_info, String.valueOf(result)));
        imgAli = (ImageView) findViewById(R.id.img_alipay);
        imgBlance = (ImageView) findViewById(R.id.img_balance);

        imgCoupon = (ImageView) findViewById(R.id.img_coupon);
        layCoupon = findViewById(R.id.lay_coupon);
        layCoupon.setEnabled(false);
        layCoupon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedCoupon != null) {
                    if (callback != null) callback.onCouponClick();
                }
            }
        });

        btnUp = (Button) findViewById(R.id.btn_up);
        btnUp.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                requestAliPay();
            }
        });

        ((AnimationDrawable) imgCoupon.getBackground()).start();

        View.OnClickListener onWayChangedListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.lay_alipay:
                        currWay = WAY_ALI;
                        imgAli.setImageResource(R.mipmap.checkbox_checked);
                        imgBlance.setImageResource(R.mipmap.checkbox_uncheck);
                        layCoupon.setEnabled(true);
                        txCouponTitle.setTextColor(0xFF05131A);
                        txCoupon.setTextColor(0xFF05131A);
                        txFinalPrice.setText(App.i().getString(R.string.date_pay_value, String.valueOf(price)));
                        break;
                    case R.id.lay_balance:
                        currWay = WAY_BALANCE;
                        imgAli.setImageResource(R.mipmap.checkbox_uncheck);
                        imgBlance.setImageResource(R.mipmap.checkbox_checked);
                        layCoupon.setEnabled(false);
                        txCouponTitle.setTextColor(0xFFB3B3B3);
                        txCoupon.setTextColor(0xFFB3B3B3);
                        txFinalPrice.setText(App.i().getString(R.string.date_pay_value, String.valueOf(originalPrice)));
                        break;
                }
            }
        };

        findViewById(R.id.lay_alipay).setOnClickListener(onWayChangedListener);
        findViewById(R.id.lay_balance).setOnClickListener(onWayChangedListener);

        requestWalletGet();
        requestCouponGet(true);
    }

    public void setData(long oid, float price, long bookid) {
        this.oid = oid;
        this.price = price;
        this.originalPrice = price;
        this.bookid = bookid;
        txPrice.setText(App.i().getString(R.string.date_pay_value_2, String.valueOf(price)));
    }

    public void setDataByNewCoupon(Coupon coupon) {
        this.selectedCoupon = coupon;
        txCoupon.setText(selectedCoupon != null ? App.i().getString(R.string.date_pay_value, String.valueOf((int) selectedCoupon.getAmount())) : App.i().getString(R.string.date_pay_coupon_empty));

        price = selectedCoupon != null ? ((price - selectedCoupon.getAmount())) : price;
        if (price < 0) price = 0.01f;

        txFinalPrice.setText(App.i().getString(R.string.date_pay_value, String.valueOf(price)));
    }

    private void requestAliPay() {
        if (currWay == WAY_ALI) {
            String body = String.valueOf(App.i().getUser().getId()) + ",";
            if (selectedCoupon != null) {
                body = body + selectedCoupon.getId();
            }

            if (App.DEBUG_MODE) price = 0.01f; // test

            String tradeNo = makeRandomValue(16) + oid;
            String serverUrl = PnwHttpManager.URL_SERVICE_PAY_NOTIFY;
            LogUtil.t("requestAliPay(oid:" + oid + " price:" + price + " body:" + body + " serverUrl:" + serverUrl + ")");
            PayManager.pay(((BaseActivity) getContext()), tradeNo, price, App.i().getString(R.string.pay_name), body, serverUrl
                    , new PayManager.PayResultListener() {
                @Override
                public void onSuccess() {
                    EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_DATE_INFO_STATUS_PAY_SUCCESS));
                    ((BaseActivity) getContext()).finish();
                }

                @Override
                public void onDealing() {
                }

                @Override
                public void onFail() {
                }
            });
        } else if (currWay == WAY_BALANCE) {
            Float amount = App.i().getUser().getAmount();
            int result = amount != null ? (int) amount.floatValue() : 0;
            if (result < originalPrice) {
                BaseUtil.showToast(R.string.date_pay_balance_fail);
            } else {
                requestOrderPayOrderWithBalance();
            }
        }
    }

    private void requestOrderPayOrderWithBalance() {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(getContext()).setCanCancel(false).create();
        dlgLoading.show();
        PnwHttpManager.Order.payOrderWithBalance(((BaseActivity) getContext()).TAG, oid, new PnwOkCallbackAdapter<HttpResp>() {
            @Override
            public void onResponse(HttpResp response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    User login = App.i().getUser();
                    int result = login.getAmount() != null ? (int) login.getAmount().floatValue() : 0;
                    login.setAmount(result - originalPrice);
                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, login));

                    EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_DATE_INFO_STATUS_PAY_SUCCESS));
                    ((BaseActivity) getContext()).finish();
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private void requestWalletGet() {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(getContext()).setCanCancel(false).create();
        dlgLoading.show();

        PnwHttpManager.Wallet.get(((BaseActivity) getContext()).TAG, new PnwOkCallbackAdapter<HttpRespData<Balance>>() {
            @Override
            public void onResponse(HttpRespData<Balance> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    float result = response.data.amount != null ? response.data.amount.floatValue() : 0;
                    User login = App.i().getUser();
                    login.setAmount(result);
                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, login));

                    txBalanceInfo.setText(App.i().getString(R.string.date_pay_way_balance_info, String.valueOf(result)));
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                dlgLoading.dismiss();
                //
            }
        });
    }

    private void requestCouponGet(boolean is_valid) {
        PnwHttpManager.Coupon.get(((BaseActivity) getContext()).TAG, is_valid, new PnwOkCallbackAdapter<HttpRespData<List<com.paishen.peiniwan.frame.http.entity.Coupon>>>() {
            @Override
            public void onResponse(HttpRespData<List<com.paishen.peiniwan.frame.http.entity.Coupon>> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    CouponDao couponDao = App.i().getCurrDaoSession().getCouponDao();
                    List<Coupon> couponList = new ArrayList<>();

                    for (com.paishen.peiniwan.frame.http.entity.Coupon c : response.data) {
                        Coupon coupon = ModelConverter.mergeOrReplace(null, c, App.i().getUser().getId());
                        couponList.add(coupon);
                        if (selectedCoupon == null || coupon.getAmount() > selectedCoupon.getAmount()) {
                            selectedCoupon = coupon;
                        }
                    }
                    couponDao.insertOrReplaceInTx(couponList);

                    ((AnimationDrawable) imgCoupon.getBackground()).stop();
                    imgCoupon.setVisibility(View.GONE);
                    layCoupon.setEnabled(true);
                    txCoupon.setText(selectedCoupon != null ? App.i().getString(R.string.date_pay_value, String.valueOf((int) selectedCoupon.getAmount())) : App.i().getString(R.string.date_pay_coupon_empty));


                    price = selectedCoupon != null ? ((price - selectedCoupon.getAmount())) : price;
                    if (price < 0) price = 0.01f;
                    txFinalPrice.setText(App.i().getString(R.string.date_pay_value, String.valueOf(price)));

                    btnUp.setEnabled(true);
                    btnUp.setTextColor(0xFFFFFFFF);
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                ((AnimationDrawable) imgCoupon.getBackground()).stop();
                imgCoupon.setVisibility(View.GONE);
                layCoupon.setEnabled(false);

            }
        });
    }
}
